<template>
  <div class="order-assign-container">
    <div class="page-header">
      <div class="header-title">
        <h2>分配车辆</h2>
        <span class="subtitle">为订单分配车辆和驾驶员</span>
      </div>
      <div class="header-actions">
        <el-button @click="goBack">
          <el-icon><Back /></el-icon>返回详情
        </el-button>
      </div>
    </div>

    <el-card v-loading="loading">
      <!-- 订单基本信息 -->
      <el-descriptions title="订单信息" :column="3" border>
        <el-descriptions-item label="订单号" :span="2">{{ order.orderNo }}</el-descriptions-item>
        <el-descriptions-item label="订单类型">{{ getOrderTypeName(order.orderType) }}</el-descriptions-item>
        <el-descriptions-item label="客户名称" :span="2">{{ order.customer }}</el-descriptions-item>
        <el-descriptions-item label="创建时间">{{ order.createTime }}</el-descriptions-item>
        <el-descriptions-item label="起始地址" :span="3">{{ order.fromAddress }}</el-descriptions-item>
        <el-descriptions-item label="目的地址" :span="3">{{ order.toAddress }}</el-descriptions-item>
        <el-descriptions-item label="预计提货时间">{{ order.expectedPickupTime }}</el-descriptions-item>
        <el-descriptions-item label="预计送达时间" :span="2">{{ order.expectedDeliveryTime }}</el-descriptions-item>
      </el-descriptions>

      <!-- 货物信息摘要 -->
      <div class="section-title">货物信息摘要</div>
      <el-descriptions :column="3" border>
        <el-descriptions-item label="货物类型">{{ order.goods[0].name }} 等 {{ order.goods.length }} 种</el-descriptions-item>
        <el-descriptions-item label="总数量">{{ totalQuantity }} 件</el-descriptions-item>
        <el-descriptions-item label="总重量">{{ totalWeight.toFixed(2) }} kg</el-descriptions-item>
        <el-descriptions-item label="总体积">{{ totalVolume.toFixed(2) }} m³</el-descriptions-item>
        <el-descriptions-item label="特殊要求" :span="2">{{ order.specialRequirements || '无' }}</el-descriptions-item>
      </el-descriptions>

      <!-- 分配表单 -->
      <div class="section-title">分配信息</div>
      <el-form 
        ref="assignForm"
        :model="assignForm"
        :rules="assignRules"
        label-width="120px"
        class="assign-form"
      >
        <el-form-item label="承运商" prop="carrierId">
          <el-select 
            v-model="assignForm.carrierId" 
            placeholder="请选择承运商"
            filterable
            @change="handleCarrierChange"
          >
            <el-option
              v-for="carrier in carrierOptions"
              :key="carrier.value"
              :label="carrier.label"
              :value="carrier.value"
            ></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="车辆类型" prop="vehicleTypeId">
          <el-select 
            v-model="assignForm.vehicleTypeId" 
            placeholder="请选择车辆类型"
            @change="filterVehicles"
          >
            <el-option
              v-for="type in vehicleTypeOptions"
              :key="type.value"
              :label="type.label"
              :value="type.value"
            ></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="车辆" prop="vehicleId">
          <el-select 
            v-model="assignForm.vehicleId" 
            placeholder="请选择车辆"
            filterable
            @change="handleVehicleChange"
          >
            <el-option
              v-for="vehicle in filteredVehicles"
              :key="vehicle.value"
              :label="vehicle.label"
              :value="vehicle.value"
            >
              <div class="vehicle-option">
                <span>{{ vehicle.label }}</span>
                <span class="vehicle-status" :class="vehicle.status === 'available' ? 'available' : 'busy'">
                  {{ vehicle.status === 'available' ? '空闲' : '繁忙' }}
                </span>
              </div>
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="驾驶员" prop="driverId">
          <el-select 
            v-model="assignForm.driverId" 
            placeholder="请选择驾驶员"
            filterable
          >
            <el-option
              v-for="driver in filteredDrivers"
              :key="driver.value"
              :label="driver.label"
              :value="driver.value"
            >
              <div class="driver-option">
                <span>{{ driver.label }}</span>
                <span class="driver-phone">{{ driver.phone }}</span>
                <span class="driver-status" :class="driver.status === 'available' ? 'available' : 'busy'">
                  {{ driver.status === 'available' ? '空闲' : '繁忙' }}
                </span>
              </div>
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="计划提货时间" prop="plannedPickupTime">
          <el-date-picker
            v-model="assignForm.plannedPickupTime"
            type="datetime"
            placeholder="选择日期时间"
            style="width: 100%"
          ></el-date-picker>
        </el-form-item>

        <el-form-item label="计划送达时间" prop="plannedDeliveryTime">
          <el-date-picker
            v-model="assignForm.plannedDeliveryTime"
            type="datetime"
            placeholder="选择日期时间"
            style="width: 100%"
          ></el-date-picker>
        </el-form-item>

        <el-form-item label="路线规划" prop="routePlan">
          <el-input
            v-model="assignForm.routePlan"
            type="textarea"
            rows="3"
            placeholder="请输入路线规划信息"
          ></el-input>
        </el-form-item>

        <el-form-item label="特殊指示" prop="specialInstructions">
          <el-input
            v-model="assignForm.specialInstructions"
            type="textarea"
            rows="3"
            placeholder="请输入特殊指示"
          ></el-input>
        </el-form-item>
      </el-form>

      <!-- 地图预览 -->
      <div class="section-title">路线预览</div>
      <div class="map-container">
        <div class="map-placeholder">
          <el-empty description="地图加载中...">
            <template #image>
              <el-icon style="font-size: 60px"><Location /></el-icon>
            </template>
            <template #description>
              <p>此处将显示从 {{ order.fromAddress }} 到 {{ order.toAddress }} 的路线图</p>
              <p class="map-distance" v-if="routeDistance">预计距离: {{ routeDistance }} km</p>
              <p class="map-duration" v-if="routeDuration">预计时间: {{ routeDuration }}</p>
            </template>
          </el-empty>
        </div>
      </div>

      <!-- 提交按钮 -->
      <div class="form-actions">
        <el-button @click="goBack">取消</el-button>
        <el-button type="primary" @click="submitAssignment" :loading="submitting">确认分配</el-button>
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Back, Location } from '@element-plus/icons-vue'

const router = useRouter()
const route = useRoute()

// 加载状态
const loading = ref(true)
const submitting = ref(false)

// 订单数据
const order = ref({
  id: 1,
  orderNo: 'TMS-2025031401',
  orderType: 'normal',
  customer: '北京物流科技有限公司',
  customerId: 'customer1',
  fromAddress: '北京市朝阳区建国路88号',
  toAddress: '上海市浦东新区张江高科技园区',
  sender: '张三',
  senderPhone: '13800138000',
  receiver: '李四',
  receiverPhone: '13900139000',
  expectedPickupTime: '2025-03-15 09:00:00',
  expectedDeliveryTime: '2025-03-16 18:00:00',
  status: 'confirmed',
  createTime: '2025-03-14 10:15:22',
  specialRequirements: '货物易碎，小心轻放',
  goods: [
    { 
      name: '电子设备', 
      quantity: 10, 
      weight: 500, 
      volume: 2,
      packageType: 'carton',
      remarks: '小心轻放'
    }
  ]
})

// 计算总数量
const totalQuantity = computed(() => {
  return order.value.goods.reduce((sum, item) => sum + (item.quantity || 0), 0)
})

// 计算总重量
const totalWeight = computed(() => {
  return order.value.goods.reduce((sum, item) => sum + (item.weight || 0), 0)
})

// 计算总体积
const totalVolume = computed(() => {
  return order.value.goods.reduce((sum, item) => sum + (item.volume || 0), 0)
})

// 路线信息
const routeDistance = ref('320')
const routeDuration = ref('4小时30分钟')

// 承运商选项
const carrierOptions = [
  { value: 'carrier1', label: '京东物流' },
  { value: 'carrier2', label: '顺丰速运' },
  { value: 'carrier3', label: '德邦物流' },
  { value: 'carrier4', label: '安能物流' }
]

// 车辆类型选项
const vehicleTypeOptions = [
  { value: 'type1', label: '小型面包车' },
  { value: 'type2', label: '中型厢式货车' },
  { value: 'type3', label: '大型厢式货车' },
  { value: 'type4', label: '集装箱车' },
  { value: 'type5', label: '冷藏车' }
]

// 车辆选项
const vehicleOptions = [
  { value: 'vehicle1', label: '京A12345', carrierId: 'carrier1', typeId: 'type2', status: 'available' },
  { value: 'vehicle2', label: '京B67890', carrierId: 'carrier1', typeId: 'type3', status: 'busy' },
  { value: 'vehicle3', label: '京C13579', carrierId: 'carrier2', typeId: 'type2', status: 'available' },
  { value: 'vehicle4', label: '京D24680', carrierId: 'carrier2', typeId: 'type4', status: 'available' },
  { value: 'vehicle5', label: '京E97531', carrierId: 'carrier3', typeId: 'type3', status: 'available' },
  { value: 'vehicle6', label: '京F86420', carrierId: 'carrier3', typeId: 'type5', status: 'busy' },
  { value: 'vehicle7', label: '京G11111', carrierId: 'carrier4', typeId: 'type2', status: 'available' },
  { value: 'vehicle8', label: '京H22222', carrierId: 'carrier4', typeId: 'type3', status: 'available' }
]

// 驾驶员选项
const driverOptions = [
  { value: 'driver1', label: '王师傅', carrierId: 'carrier1', phone: '13811112222', status: 'available' },
  { value: 'driver2', label: '李师傅', carrierId: 'carrier1', phone: '13833334444', status: 'busy' },
  { value: 'driver3', label: '赵师傅', carrierId: 'carrier2', phone: '13855556666', status: 'available' },
  { value: 'driver4', label: '钱师傅', carrierId: 'carrier2', phone: '13877778888', status: 'available' },
  { value: 'driver5', label: '孙师傅', carrierId: 'carrier3', phone: '13899990000', status: 'available' },
  { value: 'driver6', label: '周师傅', carrierId: 'carrier3', phone: '13800001111', status: 'busy' },
  { value: 'driver7', label: '吴师傅', carrierId: 'carrier4', phone: '13822223333', status: 'available' },
  { value: 'driver8', label: '郑师傅', carrierId: 'carrier4', phone: '13844445555', status: 'available' }
]

// 筛选后的车辆
const filteredVehicles = ref([])

// 筛选后的驾驶员
const filteredDrivers = ref([])

// 分配表单
const assignForm = reactive({
  carrierId: '',
  vehicleTypeId: '',
  vehicleId: '',
  driverId: '',
  plannedPickupTime: '',
  plannedDeliveryTime: '',
  routePlan: '',
  specialInstructions: ''
})

// 表单验证规则
const assignRules = {
  carrierId: [
    { required: true, message: '请选择承运商', trigger: 'change' }
  ],
  vehicleTypeId: [
    { required: true, message: '请选择车辆类型', trigger: 'change' }
  ],
  vehicleId: [
    { required: true, message: '请选择车辆', trigger: 'change' }
  ],
  driverId: [
    { required: true, message: '请选择驾驶员', trigger: 'change' }
  ],
  plannedPickupTime: [
    { required: true, message: '请选择计划提货时间', trigger: 'change' }
  ],
  plannedDeliveryTime: [
    { required: true, message: '请选择计划送达时间', trigger: 'change' }
  ]
}

// 表单引用
const assignForm = ref(null)

// 获取订单类型名称
const getOrderTypeName = (type) => {
  const typeMap = {
    'normal': '普通运输',
    'express': '快速运输',
    'cold': '冷链运输',
    'dangerous': '危险品运输'
  }
  return typeMap[type] || '未知'
}

// 处理承运商变更
const handleCarrierChange = (carrierId) => {
  // 重置车辆和驾驶员选择
  assignForm.vehicleId = ''
  assignForm.driverId = ''
  
  // 筛选该承运商的驾驶员
  filteredDrivers.value = driverOptions.filter(driver => driver.carrierId === carrierId)
  
  // 如果已选择车辆类型，则筛选车辆
  if (assignForm.vehicleTypeId) {
    filterVehicles()
  } else {
    // 否则只按承运商筛选
    filteredVehicles.value = vehicleOptions.filter(vehicle => vehicle.carrierId === carrierId)
  }
}

// 筛选车辆
const filterVehicles = () => {
  if (assignForm.carrierId && assignForm.vehicleTypeId) {
    filteredVehicles.value = vehicleOptions.filter(
      vehicle => vehicle.carrierId === assignForm.carrierId && 
                vehicle.typeId === assignForm.vehicleTypeId
    )
  } else if (assignForm.carrierId) {
    filteredVehicles.value = vehicleOptions.filter(
      vehicle => vehicle.carrierId === assignForm.carrierId
    )
  } else if (assignForm.vehicleTypeId) {
    filteredVehicles.value = vehicleOptions.filter(
      vehicle => vehicle.typeId === assignForm.vehicleTypeId
    )
  } else {
    filteredVehicles.value = []
  }
}

// 处理车辆变更
const handleVehicleChange = (vehicleId) => {
  // 可以根据车辆信息更新其他表单项
  const selectedVehicle = vehicleOptions.find(v => v.value === vehicleId)
  if (selectedVehicle && selectedVehicle.status === 'busy') {
    ElMessage.warning('该车辆当前处于繁忙状态，可能无法按时完成任务')
  }
}

// 返回详情
const goBack = () => {
  router.push(`/order/detail/${order.value.id}`)
}

// 提交分配
const submitAssignment = () => {
  assignForm.value.validate((valid) => {
    if (valid) {
      submitting.value = true
      
      // 模拟API调用
      setTimeout(() => {
        submitting.value = false
        
        ElMessage.success('车辆分配成功')
        router.push(`/order/detail/${order.value.id}`)
      }, 1500)
    } else {
      ElMessage.error('请完善表单信息')
      return false
    }
  })
}

onMounted(() => {
  // 获取订单ID
  const orderId = route.params.id
  
  // 实际应用中应该调用API获取订单详情
  setTimeout(() => {
    // 模拟API调用
    loading.value = false
    
    // 设置默认计划时间
    if (order.value.expectedPickupTime) {
      assignForm.plannedPickupTime = new Date(order.value.expectedPickupTime)
    }
    
    if (order.value.expectedDeliveryTime) {
      assignForm.plannedDeliveryTime = new Date(order.value.expectedDeliveryTime)
    }
  }, 500)
})
</script>

<style scoped>
.order-assign-container {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.header-title {
  display: flex;
  flex-direction: column;
}

.header-title h2 {
  margin: 0;
  font-size: 22px;
  color: #303133;
}

.subtitle {
  font-size: 14px;
  color: #909399;
  margin-top: 5px;
}

.section-title {
  font-size: 18px;
  font-weight: bold;
  margin: 30px 0 15px;
  color: #303133;
  border-left: 4px solid #409EFF;
  padding-left: 10px;
}

.assign-form {
  max-width: 800px;
  margin: 20px 0;
}

.vehicle-option, .driver-option {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
}

.vehicle-status, .driver-status {
  padding: 2px 6px;
  border-radius: 4px;
  font-size: 12px;
}

.driver-phone {
  color: #909399;
  font-size: 12px;
}

.available {
  background-color: #f0f9eb;
  color: #67c23a;
}

.busy {
  background-color: #fef0f0;
  color: #f56c6c;
}

.map-container {
  height: 300px;
  background-color: #f5f7fa;
  border-radius: 4px;
  margin-bottom: 20px;
}

.map-placeholder {
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
}

.map-distance, .map-duration {
  margin: 5px 0;
  font-size: 14px;
  color: #409EFF;
}

.form-actions {
  margin-top: 30px;
  display: flex;
  justify-content: center;
  gap: 20px;
}
</style>
